<template>
  <div class="material_receive">
    <one-title title="工位收料" @refreshData="refresh">
      <div class="mes_btn">
        <el-tooltip
          effect="dark"
          :content="receiveBtnStatus.content"
          :disabled="!receiveBtnStatus.status"
          popper-class="btn_tooltip"
          placement="bottom">
          <el-button
            v-btn-permission="'materialReceive'"
            @click="handleReceive" type="success" :class="{'is-disabled':receiveBtnStatus.status}">
            <i class="iconfont icon-btn_Save"></i>
            收料
          </el-button>
        </el-tooltip>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        :searchList="tableColConfig"
        ref="mesSearch"
        :searchResult="searchResult"
        @searchInfo="_info">
      </mes-search-comp>
      <div class="table_container">
        <el-table
          :data="listData.list"
          border
          stripe
          ref="mesTable"
          v-loading="isLoading"
          element-loading-text="数据加载中"
          style="width: 100%"
          :max-height="tableMaxHeight"
          :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
          @row-click="(row) => $refs.mesTable.toggleRowSelection(row)"
          @sort-change="_sort"
          @selection-change="handleSelectionChange"
          @filter-change="handleFilterChange">
          <el-table-column
            type="selection"
            width="40"
            align="center">
          </el-table-column>
          <mes-col-comp
            :key="index"
            v-for="(column, index) in columnList"
            :column="column">
          </mes-col-comp>
          <el-table-column
            label="操作"
            :resizable="false"
            min-width="160"
            align="center"
            fixed="right"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="jump_item" @click="checkRequiredDetails(scope.row.id)"> 要料明细</span>
              <span class="jump_item is_disabled" v-if="isClass(scope.row.materialRequestStatusValue)"> 收料明细 </span>
              <span class="jump_item" v-else @click="checkDeliveryDetails(scope.row)">收料明细</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <mes-pagination
        @updateData="init"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
    </div>
    <required-detail ref="RequiredDetail"></required-detail>
    <delivery-detail ref="DeliveryDetail"></delivery-detail>
    <receive-info ref="ReceiveInfo" @submitSuccess="init"></receive-info>
  </div>
</template>

<script>
import tableColConfig from './tableColConfig'
/* 字典组件 */
import {MaterialState} from '@/components/mesDict'
import RequiredDetail from './../../materialDistribution/materialTrack/components/RequiredDetail'
import DeliveryDetail from './../../materialDistribution/materialTrack/components/DeliveryDetail'
import ReceiveInfo from './components/ReceiveInfo'

// 配送中
const TRANSIT = 'Transit'
// 已收料
const RECEIVED = 'Received'

export default {
  name: 'materialReceive',
  components: {
    MaterialState,
    // 要料明细
    RequiredDetail,
    // 发料明细
    DeliveryDetail,
    // 收料
    ReceiveInfo
  },
  data() {
    return {
      isLoading: false, // 列表数据加载中
      materialReceiveDialog: false, // 收料弹窗是否显示
      searchData: {}, // 搜索参数
      searchResult: NaN, // 搜索结果数
      sortData: {}, // 排序参数
      selectData: [] // 选中的数据
    }
  },
  computed: {
    tableColConfig: tableColConfig, // 列配置
    // 列表数据
    listData() {
      return this.$store.state.materialReceive.listData
    },
    // 收料
    materialReceive() {
      return this.$store.state.materialReceive.materialReceive || []
    },
    // 要料状态(去除状态“要料中”和“已撤销”)
    materialRequestStatus() {
      return [{
        id: '',
        label: '全部'
      }, ...this.$store.getters.filterDictByValues('materialRequestStatus', ['Transit', 'Received'])]
    },
    // 要料状态状态初始查询条件
    materialRequestStatusIds() {
      return this.materialRequestStatus.reduce((pre, cur) => [...pre, cur.id], []).join(',')
    },
    // 列循环
    columnList() {
      return this.tableColConfig.filter(item => item.noForCol !== true && item.isShow !== false)
    },
    // 收料按钮
    receiveBtnStatus() {
      let status = false
      if (this.selectData.length > 1) {
        status = true
        return {status: status, content: '请选择一条数据'}
      }
      return {
        status: status,
        content: '请选择要料状态为"配送中"的数据'
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      let keyLabel = Object.keys(filters)[0]
      let keyId = this.$getColDictId(this.tableColConfig, keyLabel)
      this.searchData[keyId] = Object.values(filters)[0].join(',')
      this.$refs.mesTable.clearSort()
      this.sortData = {}
      this.sortData[keyLabel] = 'desc'
      this.init()
    },
    // 判断发料明细样式
    isClass(type) {
      switch (type) {
        // case TRANSIT:
        case RECEIVED:
          return false
        default:
          return true
      }
    },
    // 刷新方法
    refresh() {
      this.$refs.mesSearch.clean()
      this.$refs.mesTable.clearSort()
      this.$refs.mesTable.clearFilter()
      this.searchData = {}
      this.sortData = {}
      this.init()
    },
    // 初始化
    init(page) {
      this.isLoading = true
      let postData = {
        method: 'post',
        url: 'a/materialrequest/materialRequest/list',
        data: {
          pageNo: page ? page.pageNo : 1,
          pageSize: page ? page.pageSize : this.listData.pageSize || 15,
          sort: this.sortData
        },
        module: 'materialReceive',
        state: 'listData'
      }
      postData.data.query = JSON.parse(JSON.stringify(this.searchData))
      if (!postData.data.query.requestStatusId) {
        postData.data.query.requestStatusId = this.materialRequestStatusIds
        postData.data.query.viewSource = 1
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        if (Object.keys(this.sortData).length > 0) {
          postData.data.sort = this.sortData
        }
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 查看要料明细
    checkRequiredDetails(id) {
      this.$refs.RequiredDetail.openDialog(id)
    },
    // 查看发料明细
    checkDeliveryDetails(row) {
      if (row.materialRequestStatusValue === TRANSIT || row.materialRequestStatusValue === RECEIVED) {
        this.$refs.DeliveryDetail.openDialog(row.id, '收料明细')
      }
    },
    // 搜索
    _info(data) {
      this.searchData = data
      this.$refs.mesTable.clearFilter()
      this.$refs.mesTable.clearSort()
      this.sortData = {}
      this.init()
    },
    // 复选框选中
    handleSelectionChange(val) {
      this.selectData = val
    },
    // 扫码刷新
    handleCodeScan(value) {
      this.$refs.mesSearch.clean()
      if (value) {
        this.searchData = {
          number: value
        }
        this.init()
      } else {
        this.tipMessage('error', '无效搜索码')
      }
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 可选项过滤（要料状态只允许操作配送中）
    // optional(row) {
    //   switch (row.materialRequestStatusValue) {
    //     case 'Transit':
    //       return true
    //     default:
    //       return false
    //   }
    // },
    // 显示收料弹框
    handleReceive() {
      if (!this.selectData.length) {
        return this.tipMessage('error', '请选择一条数据')
      }
      if (this.receiveBtnStatus.status) return
      this.$refs.ReceiveInfo.openDialog(this.selectData[0].id)
    },
    // 参数拼接
    saveParams() {
      let arr = []
      this.materialReceive.map(val => {
        arr.push({
          id: val.id,
          receiveQuantity: val.receiveQuantity ? val.receiveQuantity : 0
        })
      })
      return arr
    },
    // 要料确认提交
    createBatch() {
      let ids = this.selectData.map(item => item.id)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/materialreceive',
        data: {
          materialReqId: ids.join(','),
          materialReqInvList: this.saveParams()
        },
        noCommit: true
      }).then(() => {
        this.init()
        this.materialReceiveDialog = false
        this.$message({
          type: 'success',
          message: '修改成功',
          duration: 1500,
          center: true
        })
      })
    },
    switchDialog(value) {
      this.materialReceiveDialog = value
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .material_receive {
    .disable_btn {
      color: #7e8e9f;
      cursor: not-allowed;
    }
  }
</style>
